package com.tianji.aigc.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.embedding.EmbeddingModel;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.ai.vectorstore.redis.RedisVectorStore;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.JedisPooled;

@Configuration
@Slf4j
public class RedisVectorStoreConfig {

    @Value("${spring.ai.vectorstore.redis.index-name}")
    private String indexName;

    @Value("${spring.ai.vectorstore.redis.prefix}")
    private String prefix;

    @Value("${spring.data.redis.host}")
    private String redisHost;

    @Value("${spring.data.redis.password}")
    private String redisPwd;

    private VectorStore vectorStore;

    /**JedisPooled 是一个 Redis 客户端连接池类，用于管理与 Redis 服务器的连接。
     * 使 RedisVectorStore 能够执行向量存储和检索操作
     * */
    @Bean
    public JedisPooled jedisPooled() {
        return new JedisPooled(redisHost, 6379,null,redisPwd);
    }

    @Bean
    @ConditionalOnMissingBean
    public VectorStore redisVectorStore(JedisPooled jedis,
                                        @Qualifier("dashscopeEmbeddingModel") EmbeddingModel dashscopeEmbeddingModel) {
        log.info("创建 RedisVectorStore Bean...");

        RedisVectorStore redisVectorStore = null;
        try {
            redisVectorStore = RedisVectorStore.builder(jedis, dashscopeEmbeddingModel)
                    .indexName(indexName) // 指定索引名称
                    .prefix(prefix) // 添加前缀
                    .initializeSchema(true) // 初始化索引结构
                    .build();
            this.vectorStore = redisVectorStore;
        } catch (Exception e) {
            log.error("创建 RedisVectorStore Bean 失败！", e);
        }
        log.info("RedisVectorStore Bean 创建成功！使用模型: {}", dashscopeEmbeddingModel);
        return redisVectorStore;
    }
}